--
-- Author: SuYinXiang (sue602@163.com)
-- Date: 2016-04-05 16:55:56
--

require "quickframework.init"
require "sharefunc"
local profile = require "skynet.profile"

local skynet = require("skynet")
local mysql = require("skynet.db.mysql")
local serviceAPI = require "ServiceAPI"

local nodeid,instance = ...

local db = nil
local MYSQL_CMD = {}

local SEND_CMD = {
    sendExecute = "sendExecute"
}

--连接mysql数据库
function MYSQL_CMD.connect(conf)
    local ret = false
    db = mysql.connect(conf)
    db:query("set names utf8mb4")
    assert(db,"connect to mysql server failed")
    if db then skynet.error("connect to mysql server success,dbname="..conf.database) end
    ret = true
    return ret
end

--断开数据库连接
function MYSQL_CMD.disconnect()
    local ret = nil
    if db then
        db:disconnect()
        ret = true
    end
    return ret
end

--执行sql语句
function MYSQL_CMD.execute(sql)
    local ret = nil
    if db then
        ret = db:query(sql)
    end
    return ret
end

--执行sql语句
function MYSQL_CMD.sendExecute(sql)
    local ret = nil
    if db then
        ret = db:query(sql)
        if not ret or not ret.affected_rows or ret.affected_rows ~= 1 then
            skynet.error("sql error sql=", sql)
        end
    end
end

skynet.start(function()

    --注册dispatch函数
    skynet.dispatch("lua", function(_,_,cmd, ...)
        profile.start()

        local f = assert(MYSQL_CMD[cmd])
        if SEND_CMD[cmd] then
            f(...)
        else
            local ok,ret = xpcall(f,sharefunc.exception,...)
            skynet.ret(skynet.pack(ok,ret))
        end

        local time = profile.stop()
        if time > 3 then
            local p = ti[cmd]
            if p == nil then
                p = { n = 0, ti = 0 }
                ti[cmd] = p
            end
            p.n = p.n + 1
            p.ti = p.ti + time
        end
    end)

    -- 注册 info 函数，便于 debug 指令 INFO 查询。
    skynet.info_func(function()
        dump(ti, "mysql ti=", 10)
        return ti
    end)

    serviceAPI.setSvr(skynet.self(),serviceAPI.mysqlGame,nodeid,instance)
end)
